#include "WLonLatDemGetter.h"

bool WLonLatDemGetter::loadFile(string filename)
{
	_loaded = false;
	GDALAllRegister();
	GDALDataset* ds = (GDALDataset*)GDALOpen(filename.c_str(), GA_ReadOnly);
	if (ds == 0) {
		cout << "Error, WLonLatDemGetter::loadFile: failed to load " << filename << endl;
		return false;
	}
	ds->GetGeoTransform(_trans);
	_xsize = ds->GetRasterXSize();
	_ysize = ds->GetRasterYSize();
	_demData.resize(_xsize * _ysize);
	ds->GetRasterBand(1)->RasterIO(GF_Read, 0, 0, _xsize, _ysize, _demData.data(), _xsize, _ysize, GDT_Int16, 0, 0, 0);
	GDALClose(ds);
	_loaded = true;
}
short WLonLatDemGetter::getDem(double lon, double lat, bool& isGood)
{
	if (_loaded) {
		//lon = t0+t1*ix; lat=t3+t5*iy ;
		int ix = (lon - _trans[0]) / _trans[1] + 0.5 ;
		int iy = (lat - _trans[3]) / _trans[5] + 0.5 ;
		if (ix >= 0 && ix < _xsize && iy >= 0 && iy < _ysize) {
			isGood = true;
			return _demData[iy * _xsize + ix];
		}
		else {
			isGood = false;
			return 0;
		}
	}
	else {
		isGood = false;
		return 0;
	}
}